package com.farm.sound;

import com.farm.baiduapi.Base64Util;
import com.farm.utils.ConnUtil;
import com.farm.utils.DemoException;
import com.farm.utils.TokenHolder;

import java.io.*;

import javazoom.spi.mpeg.sampled.file.MpegAudioFileReader;
import lombok.Data;
import okhttp3.*;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import javax.sound.sampled.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
@Data
public class SoundToText {
    private String path;

    private String format;

    public static final String API_KEY = "X0MXNHz7XyFyjTizCUVBuFeC";
    public static final String SECRET_KEY = "n9miFLMjNra4a9L45zVgeioepSnr7lBE";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public String run() throws IOException, JSONException {
        MediaType mediaType = MediaType.parse("application/json");
        // speech 可以通过 getFileContentAsBase64("C:\fakepath\16k.pcm") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("format",this.format);
        jsonObject.put("rate",16000);
        jsonObject.put("channel",1);
        jsonObject.put("cuid","WcuU6waRP18cTTNYRMX6v9EwY5rv42Zj");
        jsonObject.put("speech",getFileContentAsBase64(this.path,false));
        jsonObject.put("token",getAccessToken());
        jsonObject.put("len",129600);

        RequestBody body = RequestBody.create(mediaType,jsonObject.toString());
        Request request = new Request.Builder()
                .url("https://vop.baidu.com/server_api")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return response.body().string();

    }

    public String run(String base64) throws IOException, JSONException {
        MediaType mediaType = MediaType.parse("application/json");
        // speech 可以通过 getFileContentAsBase64("C:\fakepath\16k.pcm") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,第二个参数传true
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("format",this.format);
        jsonObject.put("rate",16000);
        jsonObject.put("channel",1);
        jsonObject.put("cuid","WcuU6waRP18cTTNYRMX6v9EwY5rv42Zj");
        jsonObject.put("speech",base64);
        jsonObject.put("token",getAccessToken());
        jsonObject.put("len",129600);

        RequestBody body = RequestBody.create(mediaType,jsonObject.toString());
        Request request = new Request.Builder()
                .url("https://vop.baidu.com/server_api")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return response.body().string();

    }

    /**
     * 将MP3转换为PCM（8k 16位）并返回Base64编码的PCM数据字符串。
     *
     * @param file       输入的MP3文件
     * @return Base64编码的PCM数据字符串
     */
    public String mp3ToPcmBase64(MultipartFile file) {
        try {
            AudioInputStream audioInputStream = getPcmAudioInputStream(file);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, byteArrayOutputStream);
            byte[] pcmBytes = byteArrayOutputStream.toByteArray();
            return Base64.getEncoder().encodeToString(pcmBytes);
        } catch (IOException | UnsupportedAudioFileException e) {
            e.printStackTrace();
            return null;
        }
    }

    private AudioFormat targetFormat = null;

    /**
     * 从MP3文件中获取PCM音频输入流。
     *
     * @param file 输入的MP3文件
     * @return PCM音频输入流
     * @throws IOException 如果发生I/O错误
     */
    private AudioInputStream getPcmAudioInputStream(MultipartFile file) throws IOException, UnsupportedAudioFileException {
        InputStream inputStream = file.getInputStream();
        AudioInputStream in = null;
        MpegAudioFileReader mp = new MpegAudioFileReader();
        in = mp.getAudioInputStream(inputStream);
        AudioFormat baseFormat = in.getFormat();
        targetFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16,
                baseFormat.getChannels(), baseFormat.getChannels() * 16 / 8, baseFormat.getFrameRate(), false);
        return AudioSystem.getAudioInputStream(targetFormat, in);
    }


    /**
     * 获取文件base64编码
     *
     * @param path      文件路径
     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
     * @return base64编码信息，不带文件头
     * @throws IOException IO异常
     */
    static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException, JSONException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

}
